<template>
  <div id="home" :class="'home-' + (paths.length > 1  && !hideNav ? '2': '1')">
    <!-- header -->
    <div class="header">
      <div class="header-logo lw">
        <!--<div class="logo">-->
          <!--<router-link to="/">-->
            <!--<img v-if="$config('logo.mini')" :src="$config('logo.mini')" />-->
            <!--<span v-else class="font-white f18 fb">{{webTitle}}</span>-->
          <!--</router-link>-->
        <!--</div>-->
        <!--<div class="text" v-show="0"></div>-->
        <div class="logo">
          <router-link to="/snmpManage/collection/target"><span style="color: white">SNMP采集系统</span></router-link>
        </div>
        <div class="text" >SNMP采集系统</div>
      </div>
      <!-- header-nav -->
      <div class="header-nav">
        <router-link :to="{path : '/snmpManage/collection/target'}">
          <span class="f12">首页</span>
        </router-link>
        <!--<div class="iconbtn" style="margin-right:30px;">-->
          <!--<i class="el-icon-menu"></i>-->
          <!--<span>导航&nbsp;</span>-->
          <!--<div class="over-box" style="width:200px;">-->
            <!--<ul>-->
              <!--<li v-for="(item, index) in navList" :key="index" @click="hideSubNav=[]">-->
                <!--<router-link-->
                  <!--:class="{'actived': (paths[0] && paths[0] == item.path)}"-->
                  <!--:to="{path : item.path}"-->
                <!--&gt;{{ item.name }}</router-link>-->
                <!--<span class="vbtn" v-if="0">-->
                  <!--<el-button-->
                    <!--icon="el-icon-minus"-->
                    <!--circle-->
                    <!--size="mini"-->
                    <!--@click.stop="addSubNavFav(item.path)"-->
                    <!--v-if="navFav.indexOf(item.path) != -1"-->
                  <!--&gt;</el-button>-->
                  <!--<el-button-->
                    <!--icon="el-icon-plus"-->
                    <!--type="primary"-->
                    <!--circle-->
                    <!--size="mini"-->
                    <!--@click.stop="addSubNavFav(item.path)"-->
                    <!--v-else-->
                  <!--&gt;</el-button>-->
                <!--</span>-->
              <!--</li>-->
            <!--</ul>-->
          <!--</div>-->
        <!--</div>-->
        <router-link
          :to="{path : item.path}"
          v-for="(item, index) in navList"
          :class="{'cur': (paths[0] && paths[0] == item.path)}"
          v-if="navFav.indexOf(item.path) != -1"
          :key="index"
        >
          <i :class="item.icon" style="display: none;"></i>
          <span>{{item.name}}</span>
        </router-link>
      </div>
      <!-- end header-nav -->
      <!-- header-right -->
      <div class="header-right">
        <!-- 账户 -->
        <div class="iconbtn">
          <i class="el-icon-user f20"></i>
          {{ userName }}
          <div class="over-box">
            <ul>
              <li>
                <router-link to style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                  <span class="avatar">{{ userName.substr(0, 1) }}</span>
                  {{ userName }}
                </router-link>
              </li>
              <li class="line"></li>
              <li v-if="userInfo.role === 'super'">
                <router-link :to="{path: '/member/master'}">设置主节点</router-link>
              </li>
              <li>
                <router-link :to="{path: '/user/psd'}">修改密码</router-link>
              </li>
              <!--<li>-->
                <!--<a href="javascript:;" @click.stop="clearCache">清除缓存</a>-->
              <!--</li>-->
              <li>
                <a href="javascript:void(0)" @click.stop="logOut">退出</a>
              </li>
            </ul>
          </div>
        </div>
        <!-- end账户-->

        <!-- 提醒通知 -->
        <!-- <div class="iconbtn">
          <i class="el-icon-message f20">
            <el-badge :value="3"></el-badge>
          </i>
          <div class="over-box">
            <ul>
              <li>
                <router-link to>
                  待审素材
                  <el-badge :value="3"></el-badge>
                </router-link>
              </li>
              <li>
                <router-link to>待审账户</router-link>
              </li>
            </ul>
          </div>
        </div>-->
        <!-- 提醒通知结束 -->

        <!-- 最近操作历史 -->
        <!-- <div class="iconbtn">
          <i class="el-icon-stopwatch f20"></i>
          <div class="over-box">
            <ul>
              <li v-for="(item, index) in navHistory" :key="index">
                <router-link :to="{path: item.split('#|#')[0]}">{{ item.split('#|#')[1] }}</router-link>
              </li>
              <li class="line"></li>
              <li>
                <a href="javascript:void(0)" @click.stop="navHistory=[]">清空</a>
              </li>
            </ul>
          </div>
        </div>-->
        <!-- 最近操作历史结束 -->
      </div>
      <!-- end header-right -->
    </div>
    <!-- end header -->

    <!-- left nav -->
    <div class="leftnav" style="width: 50px;z-index:1">
      <div class="leftnav_first">
        <ul>
          <li
            v-for="(item, index) in navList"
            :key="index"
            :class="currentNav == item.path ? ' current_nav first_nav_li' : 'first_nav_li'"
            @click.stop="chooseNavFirst(item)"
          >
            <span
              :class="item.icon + ' inblock'"
              style="
                  width: 50px;
                  height: 50px;
                  line-height: 50px;
                  text-align: center;
                  vertical-align: baseline;
                "
            ></span>
            <span class="f12" style="margin-left: 5px; vertical-align: top">
              {{
              item.name
              }}
            </span>
          </li>
        </ul>
      </div>
      <div class="leftnav_second" v-if="paths.length > 0 && !hideNav">
        <div class="navtitle" v-if="pathNames[0]">{{ pathNames[0] }}</div>
        <div class="navbox">
          <template v-for="item in navList" v-if="paths[0] && paths[0] == item.path">
            <dl
              v-for="(nav, index) in item.children"
              :key="index"
              :class="$route.path.startsWith(nav.path) ? 'cur_dl': ''"
            >
              <template v-if="nav.children && nav.children.length > 0">
                <dt @click.stop="showHideSubNav(nav.path)">
                  <i :class="nav.icon + ' icon'"></i>
                  {{ nav.name }}
                  <i
                    :class="hideSubNav.indexOf(nav.path) !== -1 ? 'el-icon-arrow-down arrow f14' : 'el-icon-arrow-up arrow f14'"
                  ></i>
                </dt>
                <dd
                  v-for="(child, index1) in nav.children"
                  :key="index1"
                  class="sub"
                  :kk="nav.path"
                  :class="nav.path === $route.path ? 'cur_dd':''"
                  v-show="hideSubNav.indexOf(nav.path) !== -1"
                >
                  <a
                    @click.stop="setSecondNav(index1, index)"
                    class="cursor-pointer"
                    :class="$route.path.startsWith(child.path) ? 'cur_dl':''"
                    v-if="child.children"
                  >
                    <i :class="child.icon + ' icon'" v-if="child.icon"></i>
                    {{ child.name }}
                    <i
                      :class="secondHideNav[index1] ? 'el-icon-arrow-up arrow f14' : 'el-icon-arrow-down arrow f14'"
                    ></i>
                  </a>
                  <router-link
                    v-else
                    :to="child.path"
                    :class="child.path === $route.path ? 'cur_dd':''"
                  >
                    <i :class="child.icon + ' icon'"></i>
                    {{ child.name }}
                  </router-link>
                  <div
                    v-show="secondHideNav[index + '_' + index1]"
                    v-for="(item, inx) in child.children"
                    :class="item.path === $route.path ? 'cur_dd':''"
                    :key="inx"
                  >
                    <router-link :to="{path: item.path}">
                      <i :class="item.icon + ' icon'" v-if="item.icon"></i>
                      {{ item.name }}
                    </router-link>
                  </div>
                </dd>

                <!-- <dd v-show="child.children.length" v-for="(item, inx) in child.children" :key="inx"></dd> -->
              </template>
              <template v-else>
                <dd :class="nav.path === $route.path ? 'cur_dd':''">
                  <router-link
                    :class="{'cur': (paths[1] && paths[1] == nav.path)}"
                    :to="{path: nav.path}"
                  >
                    <i :class="nav.icon + ' icon'" v-if="nav.icon"></i>
                    {{ nav.name }}
                  </router-link>
                </dd>
              </template>
            </dl>
          </template>
        </div>
      </div>
      <div :class="hideNav ? 'show-nav-btn' : 'hide-nav-btn'">
        <a href="javascript:void(0)" @click.stop="showHideNav">&nbsp;</a>
      </div>
    </div>

    <!-- end left nav -->
    <!-- content -->
    <div class="view-wrap" :class="hideNav ? 'view-wrap-50':'view-wrap-220'">
      <router-view></router-view>
    </div>
    <!-- content 结束 -->
  </div>
</template>

<script>
import { SCREEN_CHANGE, SHOW_TOKEN_ERROR } from "@store/mutation-types";
import { mapGetters, mapActions } from "vuex";
import cache from "@cache";
import { cacheConfig, cacheUserinfo, cacheUnion, cacheWeb } from "@cache";
import { Base64 } from "js-base64";
export default {
  name: "home",
  data() {
    return {
      // purview: "",
      navList: [],
      userInfo: {},
      userName: "",
      historyNav: [],
      paths: [],
      pathNames: [],
      navHistory: [],
      navFav: [],
      hideSubNav: [],
      hideNav: false,
      secondHideNav: {},
      isClear: false,
      webTitle: "",
      currentNav: "",
      navFirstList: []
    };
  },
  watch: {
    tokenError(value) {
      if (value) {
        this.$store.commit(SHOW_TOKEN_ERROR, false);
        this.message = this.$error("账号过期，请重新登录");
      }
    },
    isLogin(value) {
      if (!value) {
        this.$router.push({ name: "login" });
      }
    },
    $route(to, from) {
      // 当前路由
      if (to.redirectedFrom && to.redirectedFrom === this.currentNav) {
        if (this.$route.path.indexOf("/home") !== -1) {
          this.hideSubNav.push(
            this.$route.path.slice(0, this.$route.path.indexOf("/home"))
          );
        }
      }
      this.initPath(to.path);
    }
  },
  computed: {
    ...mapGetters(["isLogin", "tokenError", "userinfo"])
  },
  methods: {
    ...mapActions(["signOut"]),
    logOut() {
      this.signOut();
      this.$router.push({ path: "/login" });
    },
    initPath(path) {
      let that = this;
      that.paths = [];
      if (that.navList) {
        // 一级导航循环
        for (let i = 0; i < that.navList.length; i++) {
          if (path.indexOf(that.navList[i].path) == 0) {
            that.paths[0] = that.navList[i].path;
            that.pathNames[0] = that.navList[i].name;
          }
          // 二级导航循环
          if (that.navList[i].childrens) {
            for (let j = 0; j < that.navList[i].childrens.length; j++) {
              if (path.indexOf(that.navList[i].childrens[j].path) == 0) {
                that.paths[0] = that.navList[i].path;
                that.pathNames[0] = that.navList[i].name;
                that.paths[1] = that.navList[i].childrens[j].path;
                that.pathNames[1] = that.navList[i].childrens[j].name;
              }
              // if (that.navList[i].childrens[j].childrens) {
              //   // 第三级导航
              //   for (
              //     let k = 0;
              //     k < that.navList[i].childrens[j].childrens.length;
              //     k++
              //   ) {
              //     if (
              //       path.indexOf(
              //         that.navList[i].childrens[j].childrens[k].path
              //       ) == 0
              //     ) {
              //       that.paths[0] = that.navList[i].path;
              //       that.pathNames[0] = that.navList[i].name;
              //       that.paths[1] = that.navList[i].childrens[j].path;
              //       that.pathNames[1] = that.navList[i].childrens[j].name;
              //       that.paths[2] =
              //         that.navList[i].childrens[j].childrens[k].path;
              //       that.pathNames[2] =
              //         that.navList[i].childrens[j].childrens[k].name;
              //     }
              //   }
              // }
            }
          }

        }
      }
      // 计入历史
      if (that.paths.length > 0) {
        let hnav =
          that.paths[that.paths.length - 1] +
          "#|#" +
          that.pathNames[that.paths.length - 1];
        if (that.navHistory.indexOf(hnav) === -1) {
          that.navHistory.unshift(hnav);
          if (that.navHistory.length > 15) {
            that.navHistory = that.navHistory.slice(0, 15);
          }
        }
      }
    },
    //获取用户信息
    getUserInfo() {
      this.$api.get("get_userinfo").then(res => {
        if (res.status === 1) {
          // this.purview = res.data.purview_sys_detail;
          // this.userInfo = res.data;
          this.userName =
            res.data.realname ||
            res.data.uname ||
            res.data.email ||
            res.data.mobile;
          // cache.set("purview", this.purview);
          cacheUserinfo.save(res.data);
          this.userInfo = res.data
          // console.log(this.userInfo)
          this.toGetNav(res.data)
          // this.getDetail()
        }
      })
      .catch((e)=>{
        // cache.set('isMaster',false)
        // this.$router.push({ path: "/member/master" });
      });
    },
    getCfg(params) {
      this.$api
        .get("admin.get_cfg", params)
        .then(res => {
          if (res.status == 1) {
            cacheConfig.save(res.data);
          }
        })
        .catch(() => {});
    },

    // getDetail() {
    //   this.$api.get("user.get_user_detail").then(res => {
    //     if(res.status === -99){
    //       cache.set('isMaster',false)
    //       console.log(cache)
    //     }else{
    //       cache.set('isMaster',true)
    //     }
    //   })
    //   .catch(() => {});
    // },
    toGetNav(item){
      let a =[
        {has_children:2,icon:'el-icon-tickets',level:0,name:'采集管理',path:'/snmpManage',
          children:[
            {children:[],has_children:0,name:'Target',path:'/snmpManage/collection/target'},
            {children:[],has_children:0,name:'Job',path:'/snmpManage/collection/job'},
            {children:[],has_children:0,name:'集群',path:'/snmpManage/colony'},
          ]
        },
        {has_children:2,icon:'el-icon-c-scale-to-original',level:0,name:'SNMP',path:'/snmpExporter',
          children:[
            {children:[],has_children:0,name:'Module',path:'/snmpExporter/module'},
            {children:[],has_children:0,name:'Metric',path:'/snmpExporter/metric'},
          ]
        },
        {has_children:2,icon:'el-icon-s-custom',level:0,name:'会员管理',path:'/member',
          children:[
            {children:[],has_children:0,name:'会员列表',path:'/member/list'},
            {children:[],has_children:0,name:'操作日志',path:'/member/operaLog'},
          ]
        },
        // {has_children:1,icon:'el-icon-edit-outline',level:0,name:'账号管理',path:'/user',
        //   children:[
        //     {children:[],has_children:0,name:'修改密码',path:'/user/psd'},
        //   ]
        // }
      ]
      let b = [
        {has_children:2,icon:'el-icon-tickets',level:0,name:'采集管理',path:'/snmpManage',
          children:[
            {children:[],has_children:0,name:'采集目标',path:'/snmpManage/collection/target'},
            {children:[],has_children:0,name:'采集任务',path:'/snmpManage/collection/job'},
            {children:[],has_children:0,name:'集群',path:'/snmpManage/colony'},
          ]
        },
        {has_children:2,icon:'el-icon-s-custom',level:0,name:'SNMP参数',path:'/snmpExporter',
          children:[
            {children:[],has_children:0,name:'Module',path:'/snmpExporter/module'},
            {children:[],has_children:0,name:'Metric',path:'/snmpExporter/metric'},
          ]
        },
      ]

      if(item.role === 'view'|| item.role ==='edit'){
        this.navList = b;
      }else{
        this.navList = a;
      }
      this.initPath(this.$route.path);
    },
    // getNav(params) {
    //   this.$api
    //     .get("admin.get_nav", params)
    //     .then(res => {
    //       if (res.status == 1) {
    //         this.navList = res.data;
    //         res.data.forEach(el => {
    //           if (el.path === `/${this.$route.path.split("/")[1]}`) {
    //             this.navFirstList = el.children;
    //           }
    //         });
    //         this.initPath(this.$route.path);
    //       }
    //       this.getUnion();
    //     })
    //     .catch(() => {});
    // },
    showHideNav() {
      this.hideNav = !this.hideNav;
    },
    showHideSubNav(path) {
      let indexof = this.hideSubNav.indexOf(path);
      if (indexof === -1) {
        this.hideSubNav.push(path);
      } else {
        this.hideSubNav.splice(indexof, 1);
      }
    },
    addSubNavFav(path) {
      let indexof = this.navFav.indexOf(path);
      if (indexof === -1) {
        this.navFav.push(path);
      } else {
        this.navFav.splice(indexof, 1);
      }
      if (this.navFav.length > 5) {
        this.navFav = this.navFav.slice(-5);
      }
      cache.set("navFav", this.navFav);
      return false;
    },
    // 清除缓存
    clearCache() {
      // cacheUnion.delete("YY:union");
      cacheUserinfo.delete("YY:userinfo");
      cacheConfig.delete("YY:config");
      this.isClear = true;
      this.getUserInfo();
    },
    setSecondNav(inx, i) {
      let key = i + "_" + inx;
      let bool = this.secondHideNav[key];
      if (bool) {
        this.secondHideNav[key] = false;
      } else {
        this.secondHideNav[key] = true;
      }
      let obj = this.secondHideNav;
      this.secondHideNav = {};
      this.secondHideNav = obj;
      this.$set(this.secondHideNav);
    },
    chooseNavFirst(item) {
      this.currentNav = item.path;
      this.$router.push(this.currentNav);
    }
  },
  mounted() {
    this.getUserInfo();
    // this.navFav = cache.get("navFav") || [];
    // this.webTitle = cacheWeb.load("YY:web");
    // this.toGetNav()
    // 左侧图标点亮
    this.currentNav = "/" + this.$route.path.split("/")[1];
    // 默认菜单下拉框展开
    this.hideSubNav.push(
      this.$route.path.slice(0, this.$route.path.indexOf("/home"))
    );
  }
};
</script>
<style scoped lang="scss">
.actived {
  // background-color: #f3f3f3;
  opacity: 1;
}
.sub {
  .router-link-active {
    color: #fff !important;
  }
}
.leftnav {
  width: 220px;
}
.leftnav_first {
  width: 50px;
  height: calc(100vh - 50px);
  left: 0;
  top: 0;
  background-color: #333333;
  transition: all 0.4s;
  position: absolute;
  overflow: hidden;
  z-index: 1000;
}
.leftnav_first:hover {
  width: 220px;
}
.first_nav_li {
  font-size: 20px;
  color: #fff;
  height: 50px;
  line-height: 50px;
  text-align: left;
  width: 220px;
  cursor: pointer;
}
.first_nav_li:hover,
.current_nav {
  background-color: #262626;
  color: #0091ea;
}
.leftnav_second {
  margin-left: 50px;
  height: 100%;
  width: 170px;
  background-color: #e5e5e9;
}
.view-wrap-220 {
  margin-left: 220px;
}
.view-wrap-50 {
  margin-left: 50px;
}
.cur_dd {
  background: #0091ea !important;
  font-weight: 600;
  & > a {
    color: #fff !important;
  }
}
.cur_dl dt,
a.cur_dl {
  color: #0091ea !important;
}
.textoverflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

